我试图让 strokeStyle 在手机移动后从黑色变为红色,但我似乎无法让它工作!我希望能够在手机上拉起它,当我移动手机时,画布上的曲线将变为蓝色。
这是我的代码:
canvas = document.getElementById("c");
var ctx = c.getContext("2d");
for (var i = 0; i < 2000; i++) {
var j = 12.5 * i;
ctx.moveTo(-200 + j, 0);
ctx.bezierCurveTo(175 + j, 330, 1 + j, 600, j, 600);
ctx.bezierCurveTo(-150 + j, 750, 250 + j, 800, j + 75, 850);
//ctx.bezierCurveTo(200+j,850, 100+j, 1000, j, 1000);
}
window.addEventListener("devicemotion", handleDeviceMotion, true)
function handleDeviceMotion(e) {
var x = e.accelerationIncludingGravity.x;
var y = e.accelerationIncludingGravity.y;
var z = e.accelerationIncludingGravity.z;
document.getElementById("c").innerText = x;
document.getElementById("c").innerText = z;
document.getElementById("c").innerText = y;
setStrokeColor(ctx);
}
function setStrokeColor() {
document.getElementById("c").strokeStyle = "#FF0000";
}
//setBackgroundColor('x', color);
//setBackgroundColor('y', color);
//setBackgroundColor('z', color);
//function setBackgroundColor(var, color) {
// document.getElementbyId(var).color = "blue";
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
ctx.stroke();
<canvas id="c" width="1200" height="1000" style="border: 1 px solid #c3c3c3" ;>
</canvas>
不幸的是,一旦
绘制了线条,就无法更改线条的颜色。一种选择是擦除(或重置画布的状态以清理),然后使用新颜色重新绘制线条。大致如下:
var canvas = document.getElementById("c");
var ctx = c.getContext("2d");
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
function drawLines(color) {
for (var i = 0; i < 2000; i++) {
var j = 12.5 * i;
ctx.moveTo(-200 + j, 0);
ctx.bezierCurveTo(175 + j, 330, 1 + j, 600, j, 600);
ctx.bezierCurveTo(-150 + j, 750, 250 + j, 800, j + 75, 850);
}
ctx.lineWidth = 5;
ctx.strokeStyle = color;
ctx.stroke();
}
drawLines('#000000');
function handleDeviceMotion(e) {
// clear the lines
ctx.putImageData(imageData, 0, 0);
drawLines('#FF0000');
var x = e.accelerationIncludingGravity.x;
var y = e.accelerationIncludingGravity.y;
var z = e.accelerationIncludingGravity.z;
document.getElementById("c").innerText = x;
document.getElementById("c").innerText = z;
document.getElementById("c").innerText = y;
}
document.getElementById("simulateMotion").addEventListener('click', function() {
var e = {
accelerationIncludingGravity: {
x: 1,
y: 1,
z: 1
}
}
handleDeviceMotion(e);
});
<button id="simulateMotion">Simulate Motion</button>
<br/>
<br/>
<canvas id="c" width="1200" height="1000" style="border: 1 px solid #c3c3c3" ;>
</canvas>