canvas 通过图像数据点阵重新绘制图像
coderzhouyujavascriptcanvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
let img = new Image()
img.src = "./1.jpg";
// img.crossOrigin = false
let canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
img.onload = function(){
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img,0,0)
const imgData = ctx.getImageData(0,0,img.width,img.height).data
ctx.fillStyle = "#ffffff"
ctx.fillRect(0,0,img.width,img.height)
// 图片绘制 需要使用两个循环 一个绘制 x 一个绘制 y
for (let y = 0; y < img.height;y=y+1) {
for (let x = 0; x < img.width; x=x+2){
let i = (x + y*img.width)*4
let r = i
let g = i+1
let b = i+2
let a = i+3
ctx.fillStyle = `rgba(${imgData[r]},${imgData[g]},${imgData[b]},${imgData[a]})`
ctx.fillRect(x,y,1,1)
}
}
}
</script>
</body>
</html>