canvas操作单个像素

基本操作

mdn的像素学习链接
暂时没有找到canvas直接进行单个像素的操作,但是在canvas上下文中存在方法getImageData来生成一个可操作性的图像对象ImageData

其中,ImageData.data 存储了图片各个像素的rgba值,可以直接修改,然后从新渲染到canvas上。

麻烦的是canvas的缩放不能直接渲染ImageData,所以需要2个canvas元素,一个用来存储图片,一个用来缩放存储图片的canvas!

想要对图片进行像素级别的操作,就要放大图片。以下是放大一个20*30像素的ImageData对象后随机给各个像素填充颜色的基本操作,方法系数是20倍:

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
   	 <div class="map">
        <canvas id="data" hidden width="20" height="30"></canvas>
        <canvas id="map" width="400" height="600"></canvas>
      </div>
    <script src="./app.js"></script>
  </body>
</html>

app.js:


var map = document.getElementById('map')
var data = document.getElementById('data')
var mctx = map.getContext('2d')
var dctx = data.getContext('2d')
var imgData = dctx.createImageData(20, 30)

function render() {
  var row = 30,
    col
  do {
    col = 20
    do {
    // 根据行、列读取某像素点的R/G/B/A值的公式:
    // imageData.data[((行数-1)*imageData.width + (列数-1))*4 - 1 + 1/2/3/4];
      imgData.data[((row - 1) * imgData.width + (col - 1)) * 4 - 1 + 1] =
        Math.floor(Math.random() * 1000) % 255
      imgData.data[((row - 1) * imgData.width + (col - 1)) * 4 - 1 + 2] =
        Math.floor(Math.random() * 1000) % 255
      imgData.data[((row - 1) * imgData.width + (col - 1)) * 4 - 1 + 3] =
        Math.floor(Math.random() * 1000) % 255
      imgData.data[((row - 1) * imgData.width + (col - 1)) * 4 - 1 + 4] =
        Math.floor(Math.random() * 1000) % 255
    } while (col-- > 0)
  } while (row-- > 0)

// 关闭平滑过渡,如果不关闭,放大后的像素会很模糊
  mctx.imageSmoothingEnabled = false
  mctx.mozImageSmoothingEnabled = false
  mctx.webkitImageSmoothingEnabled = false
  mctx.msImageSmoothingEnabled = false

  dctx.putImageData(imgData, 0, 0)

  mctx.drawImage(data, 0, 0, 20, 30, 0, 0, 400, 600)
}

setInterval(render, 1000)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值