Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CSS to realize the stylized effect of picture mosaic

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use CSS to achieve picture mosaic style effect, the article is very detailed, has a certain reference value, interested friends must read it!

1. Introduction of image-rendering

An interesting feature in CSS is called image-rendering, which can be used by algorithms to better display scaled images.

Suppose we have a screenshot of a smaller QR code (lower left, only the diagram is unscannable), and the image will be rendered virtual after magnifying it 10 times (lower right):

At this time, add the characteristics of image-rendering: pixelated to the enlarged image, and CSS will pixel it through the algorithm to make its image outline have a sharper edge:

This feature is very suitable for single-color, clear-cut images that need to be enlarged, and can create a sense of vision of pseudo-vectors (reducing magnified distortion).

For photos with rich colors and more details, image-rendering: pixelated will create a mosaic look when used:

This is still a long way from the mosaic effect that the title of this article hopes to achieve-at present, the picture needs to be enlarged to show the effect, and we hope to cover the mosaic of the same size while keeping the size of the original image.

However, the image-rendering feature does not take effect on elements that have not been scaled:

MDN-This property has no effect on non-scaled images.

Second, the realization of mosaics with equal size of trampling pit.

The principle of equal-size mosaics is equivalent to blurring a picture first, and then sharpening the algorithm to get various small squares.

Image-rendering: pixelated helps us achieve the step of "sharpening". We have to figure out how to achieve "blur".

First of all, the blurring scheme of using the filter is not feasible, because the image-rendering is strongly related to the image scaling factor, so you should think about how you can take advantage of the zoom ability of the image.

It has to be said that the picture on WEB is very much like the smart object in Photoshop-you can change its size as much as you want (for example, magnify it many times to blur it), but when you change the image back to its original size, the image will change back to its original shape (without any distortion).

How to retain the "blurred" information of the enlarged picture is a priority problem to be solved.

Smart friends have thought that you can try to use canvas to deal with, after all, canvas can easily obtain, draw images, and draw out the image information is pure data, rather than graphics objects (Image), so by its zoom-in drawing image data and then reduce the drawing (to the original size) will be distorted (this is exactly what we want to happen).

But there are also some pitfalls:

The information displayed by the external image processed by the image-rendering: pixelated algorithm is not available to canvas because it is something in the display layer. Canvas still gets unsharpened, blurred native image content.

Adding image-rendering: pixelated to canvas doesn't make any sense if canvas itself is not scaled.

This means that you can't zoom in and sharpen the image outside the canvas, and then write it to canvas to zoom out (and iterate over it) to get the sharpened image of its original size.

3. Interesting canvas stretching

In solving the above problems, let's first take a look at an interesting feature of canvas.

If we define width and height in the canvas tag:

At the same time, canvas defines another width and height in the style:

Canvas {width: 200px; height: 200px;}

So in which size will the canvas be displayed?

The answer is to display in the size of CSS, but the content size of the canvas will be based on the width and height defined in the canvas tag. This means that although we see the canvas of 200px * 200px, its content is actually stretched (twice the width and four times the height).

Note: the canvas on the left and the original picture on the right

This is also a feature of canvas as a replaceable element-CSS cannot modify its contents. Imagine that if CSS can dynamically change the size of canvas content, it means that part of the canvas content will be cut, or more white space will be left, which is obviously not desirable. Therefore, it is a reasonable browser behavior for canvas to scale to the size specified by the style while keeping the content intact.

Using this feature of canvas, we can implement equal-size mosaics like this:

Create a canvas, specify its width and height by style, and set the image-rendering: pixelated property

Calculate the best display size of the picture (shown in a form similar to background-size: contain)

Set the width and height of the canvas (not the style) to 1 of the width and height of the style

Draw the image, the width and height of the image is the best display size of 1 inch N.

In this way, we actually draw an image with only the best size 1max N, and then change it back to the best visual size by N times magnification of canvas. Because the image is drawn by canvas, it will remain blurred after zooming back to the optimal size, thus meeting the matching needs of image-rendering.

Note: the "optimal size" mentioned here refers to the best size corresponding to "make sure the image is fully displayed" in step 2, not the original size of the picture.

Fourth, code implementation

We follow the above steps to write the corresponding code, of course, we want to be more flexible, for example, the above N can be customized by the user. In addition, the code for this chapter is available on Github.

4.1 HTML section

Mainly for the selection of picture controls, canvases, and convenient canvases to obtain images

, a text box for users to customize the zoom multiple, and the execute button:

Compression multiple: mosaicization

4.2 CSS section

We need to specify the appearance size of the canvas through the style and configure the image-rendering: pixelated feature. In addition,

The tag is just an intermediary that passes the image selected by the user to the canvas and can be hidden directly:

Canvas {display: block; border: gray solid 1px; width: 600px; height: 600px; image-rendering: pixelated;} img {display: none;}

4.3 JS section

Let imgBlobUrl; const file = document.getElementById ('file'); const img = document.getElementById (' img-raw'); const compressTimes = document.getElementById ('compress-times'); const defaultCompressTimes = compressTimes.value | 0; const canvas = document.getElementById (' canvas'); const button = document.querySelector ('button'); const boundingRect = canvas.getBoundingClientRect (); const ctx = canvas.getContext (' 2d'); const canvas_w = boundingRect.width Const canvas_h = boundingRect.height; / / set the picture size function matchImgSizeToCanvas in the form of background-size: contain (imgElem = img) {let w = imgElem.width; let h = imgElem.height; if (w > canvas_w | | h > canvas_h) {let radio = Math.max (h / canvas_h, w / canvas_w); radio = Number (radio.toFixed (2)) ImgElem.width = parseInt (w / radio); imgElem.height = parseInt (h / radio);}} / / draw an image with the size of 1xN, and the canvas width and height attribute is set to 1xN of the style width and height, thus achieving N-fold magnification of the canvas content function run () {let ct = parseInt (compressTimes.value) | | defaultCompressTimes; canvas.width = parseInt (canvas_w / ct). Canvas.height = parseInt (canvas_h / ct); ctx.drawImage (img, 0,0, parseInt (img.width / ct), parseInt (img.height / ct));} function cleanCanvas () {ctx.clearRect (0,0, canvas_w, canvas_h);} function reset () {img.removeAttribute ('width'); img.removeAttribute (' height'); cleanCanvas (); matchImgSizeToCanvas (img) Run ();} file.addEventListener ('change', function (e) {window.URL.revokeObjectURL (imgBlobUrl); const picFile = this.files [0]; imgBlobUrl = window.URL.createObjectURL (picFile); img.onload = function init () {reset ();} img.src = imgBlobUrl;}, false); button.addEventListener (' click', reset, false)

Execution effect:

After selecting the file / clicking the button, you can press the compression multiple to get the corresponding pixel style art photos.

Mosaic plug-in encapsulation

From the example above, we learned how to use the canvas feature to design equal-size mosaics, and now we try to encapsulate this function as a simple plug-in that allows the list of images on the page to Mosaicing with one click.

The implementation of the plug-in is also very simple-when the user clicks the button, insert a canvas the same size as the container (the size is set by style), then draw an image covering the canvas, and reduce the width and height attribute of the canvas to enlarge the content of the canvas:

5.1 plug-in script

/ * * @ file mosaic.js * * / class Mosaic {constructor (url, container, options = {}) {if (typeof container = 'string') {container = document.querySelector (container);} if (! url | |! container?.style) {console.error (' incorrect parameter');} this.url = url; this.options = options This.container = container; this.init ();} init () {const img = new Image (); const canvas = document.createElement ('canvas'); canvas.style.position =' absolute'; canvas.style.zIndex = 999; canvas.style.imageRendering = 'pixelated'; this.img = img; this.canvas = canvas This.ctx = canvas.getContext ('2d'); const containerBoundingRect = this.container.getBoundingClientRect (); const container_w = containerBoundingRect.width; const container_h = containerBoundingRect.height; / / initialize the canvas size through the style to the container size canvas.style.width = container_w +' px'; canvas.style.height = container_h + 'px' Img.onload = () = > {this.run (container_w, container_h);} img.src = this.url;} run (w, h) {/ / reduction multiple, which can be passed by parameter. Default is 12 const compressTimes = parseInt (this.options.compressTimes) | | 12; let compress_w = parseInt (w / compressTimes) Let compress_h = parseInt (h / compressTimes); / / modify the canvas size attribute to 1 / reduction multiple this.canvas.width = compress_w; this.canvas.height = compress_h; / / draw the picture to cover the reduced canvas this.ctx.drawImage (this.img, 0,0, compress_w, compress_h); this.container.prepend (this.canvas) This.img = null;} remove () {this.container.removeChild (this.canvas); this.canvas = null;}} export default Mosaic

5.2 plug-in usage page

/ * * @ file plugin-demo.html * * / ul {list-style: none; margin: 0; padding: 0;} li {float: left; line-height: 0; margin: 0 20px 20px 0;} li > img {max-height: 180px;} div {display: block; clear: both;}

Mosaic removal import Mosaic from'. / mosaic.js'; let liElems = document.querySelectorAll ('li'); let mosaicList = []; document.querySelector (' # generate'). Onclick = () = > {remove (); for (let I = 0; I)

< liElems.length; i++) { let liElem = liElems[i]; let url = liElem.querySelector('img').src; let mosaic = new Mosaic(url, liElem); mosaicList.push(mosaic); } } function remove() { mosaicList.forEach((mosaic) =>

{mosaic.remove ();}); mosaicList.length = 0;} document.querySelector ('# remove') .onclick = remove

Execution effect:

Click the "shop" or "remove" button to easily stylize / remove the pixels of each picture on the list.

VI. Compatibility

The compatibility of image-rendering can be found on caniuse. The current coverage is as follows:

The above is all the content of the article "how to use CSS to achieve the mosaic effect of pictures". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 204

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report