首頁 > web前端 > css教學 > 主體

看看圖片馬賽克風格化效果用CSS怎麼實現?

青灯夜游
發布: 2022-03-08 20:02:41
轉載
2423 人瀏覽過

CSS怎麼給圖片加馬賽克?以下這篇文章跟大家分享一下巧用 CSS 把圖片馬賽克風格化的方法,希望對大家有幫助!

看看圖片馬賽克風格化效果用CSS怎麼實現?

一、image-rendering 介紹

CSS 中有一個有趣的特性叫做image-rendering ,它可以透過演算法來更好地顯示被縮放的圖片。 (建議學習:css影片教學

假設我們有一張尺寸較小的二維碼截圖(下方左,僅為示意圖不可掃),將其放大10 倍後影像會被虛化(下右):

看看圖片馬賽克風格化效果用CSS怎麼實現?

這時給放大的圖片加上image-rendering: pixelated 的特性,CSS 會透過演算法將其像素化展示,使其影像輪廓具有更銳利的邊緣:

看看圖片馬賽克風格化效果用CSS怎麼實現?

#該特性非常適合應用在色彩單一、輪廓分明、需要放大的圖片上,可以營造出一種偽向量的既視感(減少放大後的失真)。

對於色彩豐富、細節較多的照片,image-rendering: pixelated 使用後會營造出馬賽克的外觀:

看看圖片馬賽克風格化效果用CSS怎麼實現?

#這離本文標題所希望實現的馬賽克效果還有段距離—— 目前圖片需要被放大後才能顯示出效果,而我們希望能在保有原圖尺寸的基礎上,給圖片覆蓋等尺寸馬賽克。

然而

image-rendering 特性對尺寸未發生縮放的元素是不會生效的:

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

二、踩坑等尺寸馬賽克的實現

等尺寸馬賽克的原理相當於先把一張照片模糊化,然後再經過銳利化演算法處理得到各種小方格。 image-rendering: pixelated 幫我們實現了「銳化」的步驟,我們得想想怎麼實現「模糊」。

首先使用濾鏡的模糊方案是行不通的,因為

image-rendering

和影像縮放係數強相關,所以應當思考可以怎樣利用圖片的縮放能力。
  • 這裡得說一句,WEB 上的圖片像極了Photoshop 裡的智慧型物件- 你可以任意修改它的尺寸(例如放大很多倍讓其模糊),但最後再把圖片改回原本的大小時,圖片會變回原本的樣子(沒有任何失真)。 如何保留圖片放大後的「模糊」訊息,是優先需要解決的問題。 聰明的小夥伴已經想到了可以嘗試使用canvas 來處理,畢竟
  • canvas
  • 可以輕鬆獲取、繪製圖像,且繪製出來的圖像資訊是純數據的,而非圖形物件(Image),故經其放大繪製的圖片資料再進行縮小繪製(到原尺寸)會失真(這正好是我們所希望發生的)。 但這裡也存在一些坑:
  • 外部圖像透過
image-rendering: pixelated

演算法處理後顯示的信息,canvas#是無法拿到的,因為那是顯示層的東西。 canvas 拿到的依舊是未經銳利化的、模糊的原生圖像內容;

canvas 本身如果沒有縮放的話,給

canvas

新增image-rendering: pixelated 沒有任何意義。

這意味著你無法把圖片在canvas

外面放大銳化,然後再寫入

canvas 去縮小繪製(並不斷迭代處理)來得到銳化後的原尺寸圖片。

三、有趣的 canvas 伸展

在解決上述問題時,我們先來看看

canvas 一個有趣的特性。

如果我們在###canvas### 標籤裡定義了寬高:###
<canvas width="100" height="50" ></canvas>
登入後複製
###同時又給###canvas### 在樣式中定義了另一個寬高: ###
canvas {
  width: 200px;
  height: 200px;
}
登入後複製
###那麼###canvas### 會以哪個尺寸來顯示呢? ######答案是以 CSS 的尺寸來顯示,但畫布的內容尺寸會以畫布標籤內定義的寬高為準。這意味著雖然我們看到的是 ###200px * 200px### 的畫布,但它的內容實際上被拉伸了(寬被拉伸了 2 倍,高被拉伸了 4 倍)。 ###

看看圖片馬賽克風格化效果用CSS怎麼實現?

注:左边为画布,右边为原图

这也是 canvas 作为可替换元素的一个特性 —— CSS 无法修改其内容。试想一下,如果 CSS 可以动态地修改 canvas 内容的尺寸,意味着 canvas 的内容会被裁剪掉一部分,或者多出来一部分空白区域,这显然是不可取的。所以 canvas 在保留内容完整的前提下,整体伸缩到样式规定尺寸,是合理的浏览器行为。

利用 canvas 的这个特性,我们可以这样来实现等尺寸马赛克:

  • 创建一个画布,通过样式规定好其宽高,并设置 image-rendering: pixelated 特性;
  • 计算图片最佳展示尺寸(以类似 background-size: contain 的形式展示);
  • 将画布的宽高(非样式)设置为样式宽高的 1/N
  • 绘制图像,绘制的图像宽高为最佳展示尺寸的 1/N

如此一来,我们实际绘制了一个尺寸仅为最佳尺寸 1/N 的图像,再通过 canvasN 倍放大又变回了视觉上的最佳尺寸。图像因为走的 canvas 绘制,所以放大回最佳尺寸后会保持模糊,从而满足了 image-rendering 的匹配需求。

注:这里提到的“最佳尺寸”,指的是步骤 2 里“确保完整展示图像”所对应的最佳尺寸,而非图片原生尺寸。

四、代码实现

我们按照上方步骤来书写对应代码,当然我们希望灵活一些,例如上述的 N 可以由用户自定义。另外本章的代码可以在 Github 上获取

4.1 HTML 部分

主要为选择图片的 <input> 控件、画布、方便画布获取图像的 <img alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" >、供用户自定义缩放倍数的文本框、执行按钮:

  <input id="file" type="file" accept="image/*" />
  <canvas id="canvas"></canvas>
  <img  id="img-raw" / alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" >
  <label for="compress-times">压缩倍数:</label>
  <input id="compress-times" type="number" value="12">
  <button>马赛克化</button>
登入後複製

4.2 CSS 部分

我们需要通过样式规定好画布的外观尺寸,并配置 image-rendering: pixelated 特性。另外 <img alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" > 标签只是一个传递用户所选图片到画布的中介,可以直接隐藏:

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

    img {
      display: none;
    }
登入後複製

4.3 JS 部分

    let imgBlobUrl;
    const file = document.getElementById(&#39;file&#39;);
    const img = document.getElementById(&#39;img-raw&#39;);
    const compressTimes = document.getElementById(&#39;compress-times&#39;);
    const defaultCompressTimes = compressTimes.value | 0;
    const canvas = document.getElementById(&#39;canvas&#39;);
    const button = document.querySelector(&#39;button&#39;);

    const boundingRect = canvas.getBoundingClientRect();
    const ctx = canvas.getContext(&#39;2d&#39;);
    const canvas_w = boundingRect.width;
    const canvas_h = boundingRect.height;

    // 以 background-size: contain 形式设置图片尺寸
    function matchImgSizeToCanvas(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);
      }
    }

    // 绘制 1/N 大小的图像,画布宽高属性设为样式宽高的 1/N,从而实现画布内容的 N 倍放大
    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(&#39;width&#39;);
      img.removeAttribute(&#39;height&#39;);
      cleanCanvas();
      matchImgSizeToCanvas(img);
      run();
    }

    file.addEventListener(&#39;change&#39;, 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(&#39;click&#39;, reset, false);
登入後複製

执行效果:

看看圖片馬賽克風格化效果用CSS怎麼實現?

选中文件/点击按钮后,能按压缩倍数得到对应的像素风格艺术照。

五、Mosaic 插件封装

通过上方示例我们学习了如何利用 canvas 特性来设计等尺寸的马赛克效果,现在我们尝试把该功能封装为一个简易插件,可以让页面上的图片列表一键 Mosaicing。

插件的实现方案也很简单 —— 用户点击按钮时,往图片容器上插入一个和容器等尺寸的画布(尺寸通过样式设置),再绘制覆盖画布的图像,并缩小画布的宽高属性来放大画布内容:

5.1 插件脚本

/** @file mosaic.js **/

class Mosaic {
    constructor(url, container, options = {}) {
        if (typeof container === &#39;string&#39;) {
            container = document.querySelector(container);
        }

        if (!url || !container?.style) {
            console.error(&#39;参数不正确&#39;);
        }

        this.url = url;
        this.options = options;
        this.container = container;

        this.init();
    }
    init() {
        const img = new Image();
        const canvas = document.createElement(&#39;canvas&#39;);
        canvas.style.position = &#39;absolute&#39;;
        canvas.style.zIndex = 999;
        canvas.style.imageRendering = &#39;pixelated&#39;;
        this.img = img;
        this.canvas = canvas;
        this.ctx = canvas.getContext(&#39;2d&#39;);
        const containerBoundingRect = this.container.getBoundingClientRect();
        const container_w = containerBoundingRect.width;
        const container_h = containerBoundingRect.height;

        // 通过样式初始化画布尺寸为容器尺寸
        canvas.style.width = container_w + &#39;px&#39;;
        canvas.style.height = container_h + &#39;px&#39;;

        img.onload = () => {
            this.run(container_w, container_h);
        }

        img.src = this.url;
    }
    run(w, h) {
        // 缩小倍数,可以由参数传入,默认为 12
        const compressTimes = parseInt(this.options.compressTimes) || 12;
        let compress_w = parseInt(w / compressTimes);
        let compress_h = parseInt(h / compressTimes);
        // 修改画布尺寸属性为 1/缩小倍数
        this.canvas.width = compress_w;
        this.canvas.height = compress_h;
        // 绘制图片覆盖缩小后的画布
        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 插件使用页

/** @file plugin-demo.html **/
<head>
  <style>
    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;
    }
  </style>
</head>

<body>
  <ul>
    <li><img  src="./assert/0.png" / alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" ></li>
    <li><img  src="./assert/1.png" / alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" ></li>
    <li><img  src="./assert/2.png" / alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" ></li>
    <li><img  src="./assert/3.png" / alt="看看圖片馬賽克風格化效果用CSS怎麼實現?" ></li>
  </ul>
  <div>
    <button id="generate">铺上马赛克</button>
    <button id="remove">移除马赛克</button>
  </div>


  <script type="module">
    import Mosaic from &#39;./mosaic.js&#39;;

    let liElems = document.querySelectorAll(&#39;li&#39;);
    let mosaicList = [];

    document.querySelector(&#39;#generate&#39;).onclick = () => {
      remove();
      for (let i = 0; i < liElems.length; i++) {
        let liElem = liElems[i];
        let url = liElem.querySelector(&#39;img&#39;).src;
        let mosaic = new Mosaic(url, liElem);
        mosaicList.push(mosaic);
      }
    }

    function remove() {
      mosaicList.forEach((mosaic) => {
        mosaic.remove();
      });
      mosaicList.length = 0;
    }

    document.querySelector(&#39;#remove&#39;).onclick = remove;

  </script>
</body>
登入後複製

执行效果:

看看圖片馬賽克風格化效果用CSS怎麼實現?

点击“铺上”或“移除”按钮,可以轻松实现/移除列表上各图片的像素风格化。

六、兼容性

image-rendering 的兼容性可以从 caniuse 上查到,目前覆盖率如下:

看看圖片馬賽克風格化效果用CSS怎麼實現?

影响较大的主要还是在 IE、UC,以及安卓 4.4.4 版本的浏览器,需要酌情考虑是否在产品上使用此 CSS 特性。


以上便是本文全部内容,相关代码可以在 Github 上获取(地址:https://github.com/VaJoy/BlogDemo3/tree/main/220226-pixelated)。

希望能令你有所收获,共勉~

(學習影片分享:web前端入門教學

以上是看看圖片馬賽克風格化效果用CSS怎麼實現?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:juejin.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!