我尝试使用工具来更改我想要绘制的线条的颜色
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];
};
如何通过点击工具上的颜色来更改笔触样式?
答案 0 :(得分: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;
//...