画布canvas绘制实现探照灯的效果 跟随鼠标移动

var width = document.body.clientWidth / 2;
var height = document.body.clientHeight;
// var width = window.innerWidth / 2;
// var height = window.innerHeight;
console.log("width:",width)
console.log("height:",height)
var height2 = width * 1.25;
var canvas = document.getElementById("bg_right");
var ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
var img = new Image();

window.onresize = function() {
if(document.body.clientWidth>1200){
width = window.innerWidth / 2;
height = window.innerHeight;
height2 = width * 1.25;
drawBack()
// if (height2<height) {
// var height3=height-height2;
// ctx.beginPath();
// ctx.rect(0,height2,width,height3);
// ctx.fillStyle="#ffffff";
// ctx.fill();
// }
}
}
img.onload = function() {
// 将图片画到canvas上面上去!
drawBack()
}
img.src = "./images/huabubg.png";
function drawBack() { //创建目标图片
ctx.clearRect(0, 0, width, height);
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, 0, 0, width, height2);
// ctx.drawImage(img, 30, 100,1000,1000,0,0,width,height);
if(height2 < height) {
var height3 = height - height2;
ctx.beginPath();
ctx.rect(0, height2-1, width, height3);
ctx.fillStyle = "#ffffff";
ctx.fill();
}
}
function Move(e) {
ctx.clearRect(0, 0, width, height);
drawBack()
ctx.beginPath() //开始一条路径,或重置当前的路径。
// ctx.arc(e.offsetX, e.offsetY, 50, 0, Math.PI * 2)
ctx.arc(e.layerX, e.layerY, 50, 0, Math.PI * 2)
ctx.strokeStyle = '#fff'; //绘制形状边框色
ctx.lineWidth = 10; //绘制图形的线条宽度
ctx.globalCompositeOperation = "source-over"; //在目标图像上显示源图像。
ctx.stroke() //会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径
// show(e.offsetX, e.offsetY, 50)
show(e.layerX, e.layerY, 50)
}
function Out() { //鼠标指针移出执行
ctx.clearRect(0, 0, width, height);
drawBack()
}
function show(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2)
// context.fillStyle = '#000' //填充颜色
ctx.globalCompositeOperation = "destination-out"; // 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。
ctx.fill() //填充当前的图形或者路径
}

// var width = document.body.clientWidth/2;
// var height = document.body.clientHeight;
// var canvas=document.getElementById("bg_right");
// var ctx = canvas.getContext('2d');
// canvas.width=width;
// canvas.height=height;
// var img = new Image();
// img.onload=function(){
// ctx.globalCompositeOperation = "source-over";
// ctx.drawImage(img, 0, 0,width,height);
// }
// img.src="./images/huabubg.png";
// //鼠标移动事件
// function Move(e) {
// canvas.height=height;
// ctx.globalCompositeOperation = "source-over";
// ctx.drawImage(img, 0, 0,width,height);
// ctx.arc(e.layerX, e.layerY, 50, 0, Math.PI * 2)
// ctx.strokeStyle = '#fff'; //绘制形状边框色
// ctx.lineWidth = 10; //绘制图形的线条宽度
// ctx.beginPath(); //开始绘制
// ctx.arc(e.layerX, e.layerY, 60, 0, Math.PI * 2) //画圆
// ctx.globalCompositeOperation = "destination-out"; //圆内透明
// ctx.fill(); //填充
// }
// function Out(){
//
// }

猜你喜欢

转载自www.cnblogs.com/zjboke/p/12063488.html