2018-09

博客分类: 江河计划-月总结

2018-09

算法

最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.stack = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.stack.push(x);
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.stack.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.stack[this.stack.length - 1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    if(!this.stack.length){
        return false;
    }
    var min = this.stack[0];
    for(var i=1; i<this.stack.length; i++){
        this.stack[i] < min && (min = this.stack[i])
    }
    return min;
};

/** 
 * Your MinStack object will be instantiated and called as such:
 * var obj = Object.create(MinStack).createNew()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

Fizz Buzz

写一个程序,输出从 1 到 n 数字的字符串表示。

  1. 如果 n 是3的倍数,输出“Fizz”;

  2. 如果 n 是5的倍数,输出“Buzz”;

3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。

var fizzBuzz = function(n) {
    var res = [];
    for(var i=1; i<n+1; i++){
        if(i % 3 === 0 && i % 5 === 0){
            res.push('FizzBuzz');
        }else if(i % 3 === 0){
            res.push('Fizz');
        }else if(i % 5 === 0){
            res.push('Buzz');
        }else{
            res.push(i + '');
        }
    }
    return res
};

计数质数

统计所有小于非负整数 n 的质数的数量。

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
var countPrimes = function(n) {
    if(n<=2) return 0
    if(n<=3) return 1
    var count = 1
    var arr = new Array(n)
    for(var i = 3; i < n; i+=2) {
        if(arr[i]) continue
        count++
        for(var j = i; j < n; j = j + i) {
            arr[j] = true
        }
    }
    return count
};

3的幂

给定一个整数,写一个函数来判断它是否是 3 的幂次方。

var isPowerOfThree = function(n) {
    let str = n.toString(3);
    if (str[0] === '1' && str.slice(1) == false) return true
    else return false
};

罗马数字转整数

例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

var romanObj = {'I': 1,'V': 5,'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000};
var romanToInt = function(s) {
    let max = 0;
    let result = 0;
    for (var i = s.length - 1; i >= 0; i--) {
        var currRoman = s[i];
        var currVal = romanObj[currRoman];
        result += currVal >= max ? currVal : -currVal;
        max = Math.max(max, currVal);
    }
    return result;
};

位1的个数

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011
var hammingWeight = function(n) {
    return n.toString(2).replace(/[^1]/g,'').length
};

汉明距离

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

给出两个整数 x 和 y,计算它们之间的汉明距离。

注意: 0 ≤ x, y < 231.

示例:

输入: x = 1, y = 4

输出: 2

解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

上面的箭头指出了对应二进制位不同的位置。
var hammingDistance = function(x, y) {
    return (x^y).toString(2).replace(/[^1]/g,'').length
};

SVG 属性

SVG css 属性

使用内联样式表

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <style type="text/css">
    < ![CDATA[ circle.myGreen {
        stroke: #006600;
        fill: #00cc00;
    }

    circle.myRed {
        stroke: #660000;
        fill: #cc0000;
    }

    ]]>
    </style>
    <circle class="myGreen" cx="40" cy="40" r="24" />
    <circle class="myRed" cx="40" cy="100" r="24" />
</svg>

使用外联样式表

<?xml-stylesheet type="text/css" href="svg-stylesheet.css" ?>
<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
</svg>

path元素和其它图形元素的CSS属性:

CSS属性 描述
fill 设置图形填充色
fill-opacity 设置图形的不透明度
fill-rule 设置图形的填充规则
marker 设置沿此形状边缘线的标记
marker-start 设置起始标记
marker-mid 设置中间段标记
marker-end 设置结束标记
stroke 设置图形的描边颜色
stroke-dasharray 设置描边虚线和间隔长度
stroke-dashoffset 设置虚线描边偏移
stroke-linecap 设置描边线头样式,有效值为round,butt和square
stroke-miterlimit 设置描边连接处长度
stroke-opacity 设置描边的不透明度
stroke-width 设置描边宽度
text-rendering 设置文本渲染方式

文本CSS属性

CSS属性 描述
alignment-baseline 设置文本如何与x和y坐标对齐
baseline-shift 设置用于呈现文本的基准线偏移
dominant-baseline 设置显性基准线
glyph-orientation-horizontal 设置水平字形方向
glyph-orientation-vertical 设置垂直字形方向
kerning 设置文本的字距(字距即字母间距)

渐变CSS属性

CSS属性 描述
stop-color 设置渐变中使用的stop元素中的最终颜色
stop-opacity 设置渐变中使用的stop元素中的最终不透明度

SVG 轮廓

SVG 填充

SVG 视口和视图框

SVG 动画

set

set是SVG动画中最简单的元素。它只是在特定时间间隔过去后将属性设置为某个值。因此,形状的动画不是连续的,而是只改变属性值一次。

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="10" y="10" height="110" width="110" style="stroke:#ff0000; fill: #0000ff">
        <set attributeName="x" attributeType="XML" to="100" begin="3s" />
    </rect>
</svg>

animate

让某些属性按照帧变化

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle cx="30" cy="30" r="25" style="stroke: none; fill: #0000ff;">
        <animate attributeName="cx" attributeType="XML"
            from="30"  to="470"
            begin="0s" dur="5s"
             fill="remove" repeatCount="indefinite"/>
    </circle>
</svg>

当动画结束时,动画属性被设置为原始值(fill=”remove”设置)。如果你希望动画结束时动画属性保持最终的值不变,可以将fill属性设置为freeze。动画无限重复(repeatCount属性)。

animateTransform

发生旋转和缩放的动画

<rect x="200" y="200" width="100" height="40" style="stroke: #ff00ff; fill:none;" >
    <animateTransform attributeName="transform"
        type="rotate"
        from="0 100 100" to="360 100 100"
        begin="0s" dur="10s"
        repeatCount="indefinite"
    />
</rect>

animateMotion

根据固定的路径旋转

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="0" y="0" width="30" height="15" style="stroke: #ff0000; fill: none;">
        <animateMotion
            path="M10,50 q60,50 100,0 q60,-50 100,0"
            begin="0s" dur="10s" repeatCount="indefinite"
        />
    </rect>
</svg>

协调动画

<svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="0" y="0" width="30" height="15" style="stroke: #ff0000; fill: none;">
        <animate id="one"
            attributeName="x" attributeType="XML"
            from="0" to="400"
            begin="0s" dur="3s" fill="freeze"
        />
        <animate
            attributeName="y" attributeType="XML"
            from="0" to="50"
            begin="one.end+2s" dur="3s"
            repeatDur="10s"
            fill="freeze"
        />
    </rect>
</svg>

重复动画

组合动画

控制不同的属性运动。组合动画

<svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="10" y="10" width="40" height="20" style="stroke: #000000; fill: none;">
        <animate attributeName="x"
            attributeType="XML"
            from="10" to="400"
            begin="0s" dur="10s"
            repeatCount="indefinite"
        />
        <animate attributeName="y"
            attributeType="XML"
            from="10" to="100"
            begin="0s" dur="10s"
            fill="freeze"
            repeatCount="indefinite"
        />
    </rect>
</svg>

SVG 变换

transform 提供图形变化

SVG linearGradient 渐变

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <radialGradient id="myRadialGradient4"
        fx="5%" fy="5%" r="65%"
        spreadMethod="pad">
        <stop offset="0%"   stop-color="#00ee00" stop-opacity="1"/>
        <stop offset="100%" stop-color="#006600" stop-opacity="1" />
        </radialGradient>
    </defs>
    <rect x="340" y="10" width="100" height="100" rx="10" ry="10"
        style="fill:url(#myRadialGradient4);
        stroke: #005000; stroke-width: 3;" />
</svg>

SVG 填充图案

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <pattern id="pattern2"
            x="0" y="0" width="20" height="20"
            patternUnits="userSpaceOnUse" >
            <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" />
        </pattern>
    </defs>
    <rect x="10" y="10" width="100" height="100"
        style="stroke: #000000; fill: url(#pattern2);" />
</svg>

SVG 裁剪路径

根据 cliPath 中的形状进行裁剪

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <clipPath id="clipPath">
            <rect x="30" y="30" width="40" height="40" />
        </clipPath>
    </defs>
    <circle cx="30" cy="30" r="20"
        style="fill: #0000ff; clip-path: url(#clipPath); " />
</svg>

SVG 遮罩

与裁剪相反,确定哪些形状是可见的

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <pattern id="pattern1"
            x="10" y="10" width="20" height="20"
            patternUnits="userSpaceOnUse" >
            <circle cx="10" cy="10" r="10" style="stroke: none; fill: #999999" />
        </pattern>
        <mask id="mask5" x="0" y="0" width="200" height="100" >
            <rect x="0" y="0"  width="200" height="100"
                style="stroke:none; fill: url(#pattern1)"/>
        </mask>
    </defs>
    <text x="10" y="55" style="stroke: none; fill: #000000;">
        This text is under the rectangle
    </text>
    <rect x="1" y="1" width="200" height="100"
        style="stroke: none; fill: #0000ff; mask: url(#mask5)"/>
</svg>

SVG 滤镜

<svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <filter id="blurFilter4" x="-20" y="-20" width="200" height="200">
            <feGaussianBlur in="SourceGraphic" stdDeviation="10" />
        </filter>
    </defs>
    <rect x="20" y="20" width="90" height="90"
        style="stroke: none; fill: #00ff00; filter: url(#blurFilter4);" />
</svg>

canvas 属性

中文 API

宽高

width、height:默认宽带是 300,高度是 150。

getContext

var context = canvas.getContext(contextType, contextAttributes);

contextType

contextAttributes

contextType参数值是’2d’,则contextAttributes支持的标准属性值为:

contextType参数值是’webgl’,则contextAttributes支持的标准属性值为:

toBlob

toBlob()方法可以Canvas图像对应的Blob对象(binary large object)。此方法可以把Canvas图像缓存在磁盘上,或者存储在内存中,这个往往由浏览器决定。

void canvas.toBlob(callback, mimeType, quality);

toDataURL

Canvas本质上就是一个位图图像,因此,浏览器提供了若干API可以将Canvas图像转换成可以作为IMG呈现的数据,其中最老牌的方法就是HTMLCanvasElement.toDataURL(),此方法可以返回Canvas图像对应的data URI,也就是平常我们所说的base64地址。

canvas.toDataURL(mimeType, quality);

CanvasRenderingContext2D 属性

canvas

获取当前 canvas 的引用

fillStyle

font

用于 canvas 文本绘制时候的字号字体控制。默认是 10px sans-serif

context.font = '24px SimSun, Songti SC';

// 检测字体加载完毕
// 随便设置个不认识的字体
context.font = '20px UNKNOW';
context.fillText('以梦为马,不负韶华', 10, 50);
// 弄到数据信息
var dataDefault = context.getImageData(10, 10, 50, 50).data;
// 画布擦干净
context.clearRect(0, 0, 300, 80);
// 开始进行像素检测
var detect = function () {
    context.font = '20px SYSTC';
    context.fillText('以梦为马,不负韶华', 10, 50);
    // 如果前后数据一致,说明SYSTC字体还没加载成功,继续检测
    var dataNow = context.getImageData(10, 10, 50, 50).data;
    if ([].slice.call(dataNow).join('') == [].slice.call(dataDefault).join('')) {
        context.clearRect(0, 0, 300, 80);
        requestAnimationFrame(detect);
    }
};
detect();

globalAlpha

全局的透明度,范围是 0 到 1;

context.globalAlpha = 0.5;

globalCompositeOperation

可以用来设置 canvass 图形的混合模式,可以衍生很多其他效果,例如遮罩,裁剪,以及改变绘制图形的上下层叠关系。效果

lineCap

lineDashOffset

用来制定虚线绘制的偏移距离

context.lineDashOffset = value;

lineJoin

miterLimit

当lineJoin类型是miter时候,miter效果生效的限制值。

lineWidth

线的宽度

context.lineWidth = value;

shadowBlur

模糊程度

context.shadowBlur = value;

shadowColor

阴影的颜色

context.shadowColor = color;

shadowOffsetX

阴影水平偏移大小

context.shadowOffsetX = offset;

shadowOffsetY

阴影垂直偏移大小

context.shadowOffsetY = offset;

strokeStyle

描边的样式

context.strokeStyle = color;
context.strokeStyle = gradient;
context.strokeStyle = pattern;

textAlign

文字水平对齐方式

textBaseline

文字对齐的基线

arc()

用来绘制圆弧

context.arc(x, y, radius, startAngle, endAngle [, anticlockwise]);

arcTo()

绘制标准圆角

context.arcTo(x1, y1, x2, y2, radius);

beginPath()

开始一个新路径绘制

context.beginPath();

bezierCurveTo()

绘制贝塞尔曲线

context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);

clearRect()

清除画布

context.clearRect(x, y, width, height);

clip()

裁剪

context.clip(path, fillRule);

closePath()

闭合路径

context.closePath();

createImageData

创建一个全新的空的 ImageData 对象

context.createImageData(width, height); 
context.createImageData(imagedata);

createLinearGradient

创建线性渐变对象

context.createLinearGradient(x0, y0, x1, y1);

createPattern

创建图案对象

context.createPattern(image, repetition);

createRadialGradient

创建径向渐变

context.createRadialGradient(x0, y0, r0, x1, y1, r1);

drawFocusIfNeeded

路径轮廓高亮

context.drawFocusIfNeeded(path, element);

drawImage

在画布上绘制图片,图像压缩,水印合成,图像的像素操作

context.drawImage(image, dx, dy);
context.drawImage(image, dx, dy, dWidth, dHeight);
context.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

ellipse

绘制椭圆

context.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);

fill

路径填充方法

context.fill();
context.fill(fillRule);
context.fill(path, fillRule);

fillRect

矩形填充

context.fillRect(x, y, width, height);

fillText

填充文字

context.fillText(text, x, y [, maxWidth]);

文字自动换行

CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
    if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
        return;
    }
    
    var context = this;
    var canvas = context.canvas;
    
    if (typeof maxWidth == 'undefined') {
        maxWidth = (canvas && canvas.width) || 300;
    }
    if (typeof lineHeight == 'undefined') {
        lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight);
    }
    
    // 字符分隔为数组
    var arrText = text.split('');
    var line = '';
    
    for (var n = 0; n < arrText.length; n++) {
        var testLine = line + arrText[n];
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
            context.fillText(line, x, y);
            line = arrText[n];
            y += lineHeight;
        } else {
            line = testLine;
        }
    }
    context.fillText(line, x, y);
};

getImageData

返回一个ImageData对象,其中包含Canvas画布部分或完整的像素点信息。

context.getImageData(sx, sy, sWidth, sHeight);

getLineDash

获取当前虚线的样式,就是一段实线一段空隙交替出现的条线,而这里的数字列表中的值表示的就是交替的实线和间隙的长度值。如果设置虚线时候的数字个数是奇数,这样数量就变成偶数。 例如,返回值是一个数组,则数组里面的数字会被复制和连接,数组里面的值都是数字,虚线设置为 [5,10,15] 将返回 [5,10,15,5,10,15] 。,称为数字列表。所谓虚线

context.getLineDash();

isPointInPath

用来检测某个点是否在当前路径中。beginPath 之后的才会被检测

context.isPointInPath(x, y);
context.isPointInPath(x, y, fillRule);

isPointInStroke

用来检测对应的点是否在描边路径上,则检测区域越大,描边越粗

context.isPointInStroke(x, y);
context.isPointInStroke(path, x, y);

lineTo

绘制直线以连接当前最后的子路径点和 lineTo 指定的店

context.lineTo(x, y);

measureText

测量文档的数据。返回文字的宽度

context.measureText(text)

moveTo

路径绘制的过程中将点移动

context.moveTo(x, y);

putImageData

将给定ImageData对象的数据绘制到位图上

context.putImageData(imagedata, dx, dy);
context.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);

quadraticCurveTo

绘制二次贝塞尔曲线,第一个是控制点,第二个点是终点。

context.quadraticCurveTo(cpx, cpy, x, y);