我创建了一个简单的脚本,它将在画布上生成一行。我想要达到的目标是让它从画布的中间开始,到画布的随机点结束。
这是一个演示:
const c = document.getElementById("canvas");
let ctx = c.getContext("2d");
var _x = window.getComputedStyle(c).width;
var _y = window.getComputedStyle(c).height;
//Get canvas size
var x = (c.width = Number(_x.substring(0, _x.length - 2)));
var y = (c.height = Number(_y.substring(0, _y.length - 2)));
//Turn variables from string to int
function getRandomPoint(x, y) {
//Generate random point within the canvas
var px = Math.floor(Math.random() * x);
var py = Math.floor(Math.random() * y);
var cord = [px, py];
return cord;
}
var cord = getRandomPoint(x, y);
createLine(x, y, cord[0], cord[1]);
function createLine(x, y, xk, yk) {
ctx.beginPath();
ctx.moveTo(x / 2, y / 2);
ctx.lineTo(xk, yk);
ctx.stroke();
}
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
body, html{
width:100%;
height:100%;
}
body{
background-color:#f2f2f2;
}
/* CANVAS */
canvas{
height:400px;
width:600px;
margin: 20px auto;
background-color:white;
display: block;
border: 1px solid #999;
}
<canvas id="canvas"></canvas>
如果您打开演示并看到空白的画布,请尝试刷新几次。有时该行会出现,而大多数情况下不会出现。同样,它通常不会从画布的中间开始。
我不知道为什么会这样,这是我第一次尝试使用画布,所以也许我缺少明显的东西。
最佳答案
您忘记将画布的宽度和高度放在html属性中:
const c = document.getElementById('canvas');
let ctx = c.getContext('2d');
//Get canvas size
var x = window.getComputedStyle(c).width;
var y = window.getComputedStyle(c).height;
//Turn variables from string to int
x = Number(x.substring(0,x.length-2));
y = Number(y.substring(0,y.length-2));
function getRandomPoint(x,y){
//Generate random point within the canvas
px = Math.floor(Math.random()*x);
py = Math.floor(Math.random()*y);
cord = [px, py];
return cord;
}
var cord = getRandomPoint(x,y);
createLine(x,y,cord[0],cord[1]);
function createLine(x,y,xk,yk){
ctx.moveTo(x/2,y/2);
ctx.lineTo(xk,yk);
ctx.stroke();
}
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
body, html{
width:100%;
height:100%;
}
body{
background-color:#f2f2f2;
}
/* CANVAS */
canvas{
height:400px;
width:600px;
margin: 20px auto;
background-color:white;
display: block;
border: 1px solid #999;
}
<canvas id="canvas" width="600" height="400"></canvas>
关于javascript - 在 Canvas 上生成行无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52726593/