0

我尝试使用工具来更改要绘制的线条的颜色

DIV 称为 Canvas

$(function() {
  $.each(['#f00', '#ff0', '#0f0', '#0ff', '#00f', '#f0f', '#000', '#fff'], function() {
                $('#tools').append("<a href='#canvas' data-color='" + this + "' style='width: 10px; background: " + this + ";'></a> ");
              });
              $.each([3, 5, 10, 15], function() {
                $('#tools').append("<a href='#canvas' data-size='" + this + "' style='background: #ccc'>" + this + "</a> ");
              });

});

这是画线的功能

document.getElementById('canvas').addEventListener('click', drawLine, false);
function getCursorPosition(e) {
    var x;
    var y;

    if (e.pageX != undefined && e.pageY != undefined) {
        x = e.pageX;
        y = e.pageY;
    } else {
        x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    return [x, y];
}

function drawLine(e) {
    context = this.getContext('2d');

    x = getCursorPosition(e)[0] - this.offsetLeft;
    y = getCursorPosition(e)[1] - this.offsetTop;

    if (clicks != 1) {
        clicks++;
    } else {
        context.beginPath();
        context.moveTo(lastClick[0], lastClick[1]);
        context.lineTo(x, y, 6);

        context.strokeStyle = '#000000';
        context.stroke();

        clicks = 0;
    }

    lastClick = [x, y];
};

如何通过单击工具上的颜色来更改笔触样式?

4

1 回答 1

0

如果您的画布上下文可用并在全局范围内预初始化,您可以执行以下操作:

$('#tools').append("<a href='#' onclick=\"context.strokeStyle = '" + this + "';return false;\" style='width: 10px; background: " + this + ";'></a> ");

并删除

context.strokeStyle = '#000000';

然而,这远非优雅,最好添加一个事件监听器并调用一个函数来设置strokeStyle它。

也更改此以使上下文在全球范围内可用:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

canvas.addEventListener('click', drawLine, false);

//....

function drawLine(e) {

    //context = this.getContext('2d');  //not here..
    x = getCursorPosition(e)[0] - this.offsetLeft;
    y = getCursorPosition(e)[1] - this.offsetTop;

    //...
于 2013-06-15T05:39:38.347 回答