您如何制作典型格式的照片,例如PNG,JPG等,用于像素级样式和脚本的HTML画布元素

How do you make a photograph, of a typical format, e.g., PNG, JPG, et cetera, an HTML canvas element for pixel level styling and scripting?

本文关键字:HTML 脚本 样式 布元素 元素 用于 格式 典型 何制作 照片 例如      更新时间:2023-09-26

我有一张照片,比如花.png,在这张照片中,第三列的第六个像素是 #23997E 的,我想有条件地将该像素的颜色更改为,比如说 #E54864。

这是怎么做到的。有人告诉我,HTML画布是逐像素操作图像的方式。我猜如何将照片转换为画布,然后能够指定该照片的特定像素以进行样式和脚本编写?

最简单的形式:

  1. 创建一个 javascript Image() 对象:var img=new Image() ...
  2. 使用context.drawImage(img,0,0)将该图像绘制到画布上
  3. 根据需要设置画布填充颜色:context.fillStyle='#E54864'
  4. 用所需的颜色填充像素[3,6]:context.fillRect(3,6,1,1)

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// create an Image() object
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/colorwheel1.png";
function start(){
  // draw the image onto the canvas
  ctx.drawImage(img,0,0);
  // change pixel[3,6] to  #E54864
  ctx.fillStyle='#E54864';
  ctx.fillRect(3,6,1,1);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<p>Pixel[3,6] is now colored #E54864</p>
<canvas id="canvas" width=300 height=300></canvas>