小结:
1、线性规划
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas点击事件</title></head>
<body></body>
</html>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function drawSquare(colorStr) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, 100);
ctx.lineTo(100, 100);
ctx.lineTo(100, 0);
ctx.lineTo(0, 0);
ctx.lineWidth = 6;
ctx.strokeStyle = colorStr;
ctx.stroke();
ctx.closePath();
}
function drawTri(colorStr) {
ctx.beginPath();
ctx.moveTo(50, 0);
ctx.lineTo(0, 100);
ctx.lineTo(100, 100);
ctx.lineTo(50, 0);
ctx.lineWidth = 4;
ctx.strokeStyle = colorStr;
ctx.stroke();
ctx.closePath();
}
function drawBorder() {
drawTri('red');
drawSquare('green');
}
function onSquare(p) {
if ((p.x == 0 && p.y <= 100) || (p.x <= 100 && p.y == 100)) {
return true
} else {
return false
}
}
function onTri(p) {
if ((p.y - 0) / (p.x - 50) == 100 / ( - 50)) {
return true
} else {
return false
}
}
var colorToggleSquare = {
b: true,
c0: 'black',
c1: 'yellow'
};
var colorToggleTri = {
b: true,
c0: 'blue',
c1: 'pink'
};
$(function() {
var myAction = {};
var dom = {
canvas: $('#myCanvas')
};
$.extend(myAction, {
initCanvas: function() {
drawBorder()
},
getEventPosition: function(ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) {
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) {
x = ev.offsetX;
y = ev.offsetY;
}
return {
x: x,
y: y
};
},
initEvent: function() {
dom.canvas.on('click',
function(e) {
var p = myAction.getEventPosition(e);
console.log(p);
if (onSquare(p)) {
if (colorToggleSquare.b) {
drawSquare(colorToggleSquare.c0);
} else {
drawSquare(colorToggleSquare.c1);
}
colorToggleSquare.b = !colorToggleSquare.b;
} else if (onTri(p)) {
if (colorToggleTri.b) {
drawTri(colorToggleTri.c0);
} else {
drawTri(colorToggleTri.c1);
}
colorToggleTri.b = !colorToggleTri.b;
}
});
}
});
var init = function() {
myAction.initCanvas();
myAction.initEvent();
} ();
})</script>