javascript - 在 Canvas 上生成线条无法按预期工作

标签 javascript html canvas

我创建了一个简单的脚本,它将在 Canvas 上生成一条线。我想要实现的是让它从 Canvas 的中间开始并以 Canvas 的随机点结束。

这是一个演示:

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>

如果您打开演示并看到空 Canvas ,请尝试刷新几次。有时该线会出现,但大多数时候不会出现。而且它通常不会从 Canvas 中间开始。

我不知道为什么会发生这种情况,这是我第一次尝试 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/

相关文章:

javascript - 获取元素的滚动位置以与另一个元素同步

javascript - 单击时显示幻灯片的不同片段

javascript - 如何要求浏览器缓存文件以备将来使用

javascript - 当canvas.width/height太大时canvas.toDataUrl返回 "data:;"

javascript - 使用 for 循环在 Canvas 上绘制线条

JavaScript window.open 函数在 IE7 中指示不要显示工具栏和菜单栏时显示工具栏和菜单栏

javascript - Karma-Coverage 报告显示代码被覆盖(显然没有被覆盖)

javascript - ng-click 不起作用

Javascript检查 Canvas 上的透明图像是否被点击

html - 如何为 iframe 设置自定义视口(viewport)?