【小程序】微信小程序中Canvas不显示

根据尤雨溪首页的一个三角彩带特效,想在小程序里实现这样的功能。源代码很简短,仅有十几行。源代码如下:
HTML:

<body>

<canvas width="1920" height="950"></canvas>

</body>

CSS:

canvas {

position: absolute;

top: 0;

left: 0;

z-index: 0;

width: 100%;

height: 100%;

pointer-events: none;

}

JS:

document.addEventListener('touchmove', function (e) {

e.preventDefault()

});

var c = document.getElementsByTagName('canvas')[0],

x = c.getContext('2d'),

pr = window.devicePixelRatio || 1,

w = window.innerWidth,

h = window.innerHeight,

f = 90,

q,

m = Math,

r = 0,

u = m.PI*2,

v = m.cos,

z = m.random;

c.width = w*pr;

c.height = h*pr;

x.scale(pr, pr);

x.globalAlpha = 0.6;

function i(){

x.clearRect(0,0,w,h);

q=[

{

x:0,

y:h*.7+f

},

{

x:0,

y:h*.7-f

}

];

console.log(q)

while(q[1].x < w+f)

d(q[0], q[1])

}

function d(i,j){

var k = j.x + (z()*2-0.25)*f,

n = y(j.y);

x.beginPath();

x.moveTo(i.x, i.y);

x.lineTo(j.x, j.y);

x.lineTo(k, n);

x.closePath();

r-=u/-50;

x.fillStyle = '#'+(v(r)*127+128<<16 | v(r+u/3)*127+128<<8 | v(r+u/3*2)*127+128).toString(16);

x.fill();

q[0] = q[1];

q[1] = {x:k,y:n}

}

function y(p){

var t = p + (z()*2-1.1)*f;

return (t>h||t<0) ? y(p) : t

}

document.onclick = i;

document.ontouchstart = i;

i();

我在小程序中写的代码如下:
WXML:

<view class="container">

<canvas class='first' canvas-id='first'></canvas>

</view>

WXSS:

page{

width: 100%;

height: 100%;

}

.container{

width: 100%;

height: 100%;

position: relative;

}

.first{

position: absolute;

top: 0;

left: -50%;

z-index: 0;

width: 100%;

height: 100%;

pointer-events: none;

}

JS:

Page({

data: {

},

onLoad: function () {

let w, //获取屏幕的宽

h, //获取屏幕的高

f = 90,

q,

m = Math,

r = 0,

u = m.PI * 2,

v = m.cos,

z = m.random;

wx.getSystemInfo({

success: function(res) {

w = res.screenWidth;

h = res.screenHeight

},

})

let context = wx.createCanvasContext('first'); //获取Canvas上下文

context.setGlobalAlpha(0.6)

i();

function i() {

context.clearRect(0, 0, w, h);

q = [

{

x: 0,

y: h * .7 + f

},

{

x: 0,

y: h * .7 - f

}

];

while (q[1].x < w + f)

d(q[0], q[1])

}

function d(i, j) {

context.beginPath();

context.moveTo(i.x, i.y);

context.lineTo(j.x, j.y);

var k = j.x + (z() * 2 - 0.25) * f,

n = y(j.y);

context.lineTo(k, n);

context.closePath();

r -= u / -50;

context.setFillStyle('#' + (v(r) * 127 + 128 << 16 | v(r + u / 3) * 127 + 128 << 8 | v(r + u / 3 * 2) * 127 + 128).toString(16));

context.fill();

context.draw();

q[0] = q[1];

q[1] = { x: k, y: n }

}

function y(p) {

var t = p + (z() * 2 - 1.1) * f;

return (t > h || t < 0) ? y(p) : t

}

}

})

以上代码每次运行只显示一点点:
【小程序】微信小程序中Canvas不显示

想了很久不明白为什么在微信上不显示。

回答

以上是 【小程序】微信小程序中Canvas不显示 的全部内容, 来源链接: utcz.com/a/80711.html

回到顶部