这两天被canvas完虐,搞了两天,终于写出了一个小功能,矩形可以随着鼠标移动移动,矩形也可以用drawImage替换成图片,同理,代码简单就不写注释了,在这记录一下防止遗忘
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.multi-masters.com/common/js/jquery.min.js"></script>
</head>
<body>
<div class="box" style="width: 485px;height: 485px;background-color: pink;">
<canvas class="main" width="485" height="485"></canvas>
<canvas class="thumbnail" width="200" height="200"></canvas>
</div>
</body>
<script>
var mainCanvas = document.querySelector('.main');
var mainCxt = mainCanvas.getContext('2d');
var mainW = document.querySelector('.main').clientWidth;
var mainH = document.querySelector('.main').clientHeight;
mainCanvas.onmousemove = function (e) {
var x = e.offsetX;
var y = e.offsetY;
clearR(mainCxt, 0, 0, mainCanvas.width, mainCanvas.height)
drawRect(mainCxt, x - 100 / 2, y - 100 / 2, 100, 100, 'red')
}
$('.box').mouseenter(function (e) {
console.log('ww')
$('.main').css({
display: 'block',
cursor: 'move'
});
})
$('.box').mouseleave(function (e) {
console.log('xx')
$('.main').css('display', 'none');
})
function clearR(cxt, x, y, width, height) {
cxt.clearRect(x, y, width, height);
}
function drawRect(cxt, x, y, width, height, fillColor) {
cxt.fillStyle = fillColor;
cxt.fillRect(x, y, width, height);
}
</script>
</html>