ctx.drawImage(drawImage, 0, 0, 720, 500)
}
parentId.onmousedown = e => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(drawImage, 0, 0, 720, 500)
this.flag = true
this.clickX = e.offsetX // 鼠标点击时的X
this.clickY = e.offsetY // 鼠标点击时的Y
}
parentId.onmouseup = () => {
this.flag = false
}
parentId.onmousemove = e => {
if (this.flag) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(drawImage, 0, 0, 720, 500)
ctx.beginPath()
let pixels = [] // 二维数组,每个子数组有5个值(绘制矩形左上角的X坐标、y坐标,矩形的宽、高,生成的4位随机数用于颜色值)
for (let x = 0; x < (e.offsetX - this.clickX) / 15; x++) {
for (let y = 0; y < (e.offsetY - this.clickY) / 15; y++) {
pixels.push([(x * 15 + this.clickX), (y * 15 + this.clickY), 15, 15, Math.floor(Math.random() * 9999)])
}
for (let y = 0; y > (e.offsetY - this.clickY) / 15; y--) {
pixels.push([(x * 15 + this.clickX), (y * 15 + this.clickY), 15, 15, Math.floor(Math.random() * 9999)])
}
}
for (let x = 0; x > (e.offsetX - this.clickX) / 15; x--) {
for (let y = 0; y > (e.offsetY - this.clickY) / 15; y--) {
pixels.push([(x * 15 + this.clickX), (y * 15 + this.clickY), 15, 15, Math.floor(Math.random() * 9999)])
}
for (let y = 0; y < (e.offsetY - this.clickY) / 15; y++) {
pixels.push([(x * 15 + this.clickX), (y * 15 + this.clickY), 15, 15, Math.floor(Math.random() * 9999)])
}
}
for (let i = 0; i < pixels.length; i++) {
ctx.fillStyle = '#bf' + pixels[i][4]ctx.fillRect(pixels[i][0], pixels[i][1], pixels[i][2], pixels[i][3])
}
ctx.fill()
ctx.closePath()
}
}
}
},
// 保存
dialogUpload () {
let canvas = document.getElementById('imgCanvas')
let tempImg = canvas.toDataURL('image/png')
let imgURL = document.getElementById('imgURL')
imgURL.crossOrigin = 'Anonymous'
imgURL.src = tempImg
}
}
})
</script>
</html>









