javascript - 在 javascript 数组中绘制读取值的问题 - 在 HTML5 Canvas 中绘制

标签 javascript html canvas html5-canvas

我对这一切都比较陌生,正在尝试在 html5-canvas 上绘制基本形状。我认为一个选择是使用 3.js,但我想知道是否可以不使用 3.js?每个点的 x,y 值都在数组中...请帮忙!代码和 fiddle 链接如下:

http://jsfiddle.net/mewchew/wJwL8/8/

var canvas = document.getElementById("myCanvas");

if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var width = canvas.width
    var height = canvas.height
    var xProp = 0.28
    var yProp = 0.43

    //Find canvas centerpoint - may need to change to global variable?
        function centerPoint(width, height) {
            x = Number(width) / 2;
            y = Number(height) / 2;
            return [x, y];
        }


    //Define diamond points
    xy = centerPoint(width,height);

    var pTx = newArray();
    pTx[0] = x;
    pTy[1] = x + xProp*x;
    pTy[2] = x;
    pTy[3] = x - xProp*x;
    pTy[4] = x;

    var pTy = newArray();
    pTy[0] = y;
    pTy[1] = y;
    pTy[2] = y - yProp*y;
    pTy[3] = y;
    pTy[4] = y + yProp*y;

    alert(String(pTx[1])+String(pTy[1]));  

    //Draw diamond
    ctx.beginPath();
    ctx.moveTo(pTx[0], pTy[0]);
    ctx.lineTo(pTx[1],pTy[1]);
    ctx.lineTo(pTx[2],pTy[2]);
    ctx.lineTo(pTx[3],pTy[3]);
    ctx.lineTo(pTx[4],pTy[4]);
    ctx.closePath();
    ctx.fillstyle() = "#FFFFFF"
    ctx.fill();


} else {
    // canvas-unsupported code here
    log('Fail');
}

最佳答案

您的脚本中有几个错误

第一:

newArray() 应该是 new Array()

new Array()
   ^-------- see space

第二:

var pTx = newArray();
pTx[0] = x;                    // ---> ptx ok
pTy[1] = x + xProp*x;          // ---> its pty? why? change all to ptx
pTy[2] = x;                    // ---> change to ptx
pTy[3] = x - xProp*x;          // ---> change to ptx
pTy[4] = x;                    // ---> change to ptx

应该是

var pTx = new Array();
pTx[0] = x;
pTx[1] = x + xProp*x;
pTx[2] = x;
pTx[3] = x - xProp*x;
pTx[4] = x;

第三

fillStyle 不是方法,而是属性

ctx.fillstyle() = "#FFFFFF"

应该是

ctx.fillstyle = "#FFFFFF"

Demo

关于javascript - 在 javascript 数组中绘制读取值的问题 - 在 HTML5 Canvas 中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125535/

相关文章:

javascript - 我的源映射断点在 Google Chrome 中无法正常工作

javascript - 在 Canvas 上画一个漂亮的激光(星球大战)

html - 如何为这两个组合框添加边框

jquery - 如果使用 jQuery 选中复选框,如何禁用文本框?

html - 在输入 :focus, 上设置还关注兄弟元素而不使用 javascript

javascript - 绘制圆形 Canvas 和打印 Canvas

javascript - 如何在 FabricJS 中检测 Canvas 上的空白区域?

javascript - 必须从三个不同的 HTML 表单中获取数量,并计算总价。我究竟做错了什么?

javascript - 获取单选按钮选择的值

javascript - jquery svg 变换颜色动画