Use the applet’s Canvas 2D to extract the color of a specific point

Original link: https://www.ixiqin.com/2022/07/30/canvas-2-d-extraction-using-a-small-application-specific-colors/

6ee6df690137fd06bc6166adb63caca1.png

In the applet, we can get the user’s click behavior by binding the Tap event on the Canvas canvas. When we get the coordinates corresponding to the click behavior, we can read the color of the corresponding position. And according to our needs, convert the color to the RBG color value we want.

This is the most common implementation of various color picking software that we commonly use. Of course, when it comes to the actual development process, everyone will be more or less different (involving color grading. The colors we take photos are not exactly the same as what we see. Different cameras have different color grading. Similarly, we need to add the corresponding reverse algorithm to exclude the influence of the corresponding camera’s own tuning).

For the specific implementation in the applet scenario, please refer to the following code:

Page Layout

 <view> <view><button bindtap="chooseImage">1. 选择图片</button></view> <view><canvas id="myCanvas" bindtap="onCanvasTap" type="2d" style="background-color:gray;width: 100%;margin-top: 100rpx;"></canvas></view></view>

Corresponding JS

Just like drawing a local image using the Canvas 2D API in the applet , you need to extract the Ctx of the Canvas for performing operations. When you get the coordinates of your click point relative to the upper left corner of the Canvas through bindTap, you can use <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/getImageData">getImageData</a> to extract a specific range of data. Because my purpose is to extract the color of a certain point, my third and fourth parameters are both 1 (take the width and height of a pixel).

After extracting the image data, you can extract an array of 4 elements in the data, in order, they are the four values ​​of RGBA, you can use this data according to your needs (such as zooming in and displaying it on the interface).

 Page({ data: { color: '' }, onCanvasTap(e) { const query = wx.createSelectorQuery() query.select('#myCanvas') .fields({ node: true, size: true }) .exec((res) => { const canvas = res[0].node const ctx = canvas.getContext('2d') const data = ctx.getImageData(e.detail.x, e.detail.y, 1, 1).data; const [red,gree,blue,alpha] = data; }) },});

This article is reprinted from: https://www.ixiqin.com/2022/07/30/canvas-2-d-extraction-using-a-small-application-specific-colors/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment