javascript – HTML5 Canvas:操纵个别路径

在使用HTML5画布时,如何保存javascript变量/数组的特定路径,然后对其进行操作?这是我到目前为止所做的事情:

                    ctx.beginPath();
                        ctx.moveTo(lastX,lastY);
                        ctx.lineTo(x,y);
                        ctx.lineWidth = s*2;
                        ctx.stroke();
                    ctx.closePath();

现在,我需要的是能够有时将此路径存储在数组中.然后,我需要能够返回并稍后更改数组中所有路径的颜色. (显然,我也不知道该怎么做.)

最佳答案
您可以序列化将路径绘制到javascript对象中所需的所有数据

使用javascript对象的好处是,如果需要将路径移动到其他位置(例如返回服务器),则可以进一步将对象序列化为JSON.

var path1={
    lineWidth:1,stroke:"blue",points:[{x:10,y:10},{x:100,y:50},{x:30,y:200}]
};

然后,您可以使用该对象绘制/重绘该路径

    function draw(path){

        // beginPath
        ctx.beginPath();

        // move to the beginning point of this path
        ctx.moveTo(path.points[0].x,path.points[0].y);

        // draw lines to each point on the path
        for(pt=1;pt

要更改路径的颜色,只需更改对象的stroke属性并再次调用draw():

    paths[0].stroke="orange";
    paths[1].stroke="green";
    draw();

这是代码和小提琴:http://jsfiddle.net/m1erickson/McZrH/

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小