HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<canvas id="main-score"></canvas>
const createNewCanvas = (width = 256, height = 1): HTMLCanvasElement => {
const canvas: HTMLCanvasElement = document.createElement('canvas')
canvas.width = width
canvas.height = height
return canvas
}
const getLinearGradient = (
canvas: HTMLCanvasElement,
colors: [number, string][]
): CanvasGradient | undefined => {
const linearGradient = canvas.getContext('2d')?.createLinearGradient(0, 0, canvas.width, 0)
colors.forEach(([position, color]) => {
linearGradient?.addColorStop(position, color)
})
return linearGradient
}
const getPalatteCanvasImageData = (colors: [number, string][]): Uint8ClampedArray | undefined => {
const palatteCanvas: HTMLCanvasElement = createNewCanvas()
const ctx = palatteCanvas.getContext('2d')
if (!ctx) return
ctx.fillStyle = getLinearGradient(palatteCanvas, colors) || ''
ctx.fillRect(0, 0, palatteCanvas.width, palatteCanvas.height)
return ctx.getImageData(0, 0, palatteCanvas.width, palatteCanvas.height).data
}
class Palette {
private imageData: Uint8ClampedArray | undefined
constructor(
colors: [number, string][] = [
[0, '#000'],
[1, '#fff'],
]
) {
this.imageData = getPalatteCanvasImageData(colors)
}
pickColor(pos: number): Uint8ClampedArray | undefined {
return this.imageData?.slice(pos * 4, pos * 4 + 4)
}
}
interface Config {
width: number
height: number
startAngle: number
endAngle: number
bgEndAngle: number
interval: number
total: number
lineWidth: number
bgColor: string
r: number
totalFramesLength: number
angleChangeForFrame: number
duration: number
clockwise: boolean
colors?: [number, string][]
canvasId: string
palette: any
ctx: CanvasRenderingContext2D
}
const defaultConfig: Partial<Config> = {
width: 100,
height: 100,
startAngle: 180,
endAngle: 180,
bgEndAngle: 365,
interval: 5,
total: 2000,
lineWidth: 15,
bgColor: '#cccc',
r: 100,
colors: [
[0, '#009'],
[1, '#f00'],
],
}
const precision = 2
const angleDistance1 = 1
const angleDistance2 = 1.6
const angleToRadian = (angle: number): number => (angle / 180) * Math.PI
const setCanvasStyle = (option: Config, canvas: HTMLCanvasElement): void => {
canvas.width = option.width
canvas.height = option.height
}
const setStrokeStyle = (ctx: CanvasRenderingContext2D, color: number[]): void => {
const [r, g, b, alpha] = color
ctx.strokeStyle = `rgb(${r},${g},${b},${alpha / 255})`
}
const setLineStyle = (option: Config): void => {
const ctx = option.ctx
ctx.lineWidth = option.lineWidth
ctx.globalAlpha = 1
ctx.lineCap = 'round'
}
const drawArc = (option: Config, currentFrameIndex: number): void => {
const { startAngle, bgEndAngle, width, height, ctx, bgColor, r, clockwise, angleChangeForFrame } =
option
let endAngle: number = startAngle + currentFrameIndex * angleChangeForFrame
if (Math.abs(endAngle - option.endAngle) < Math.abs(angleChangeForFrame)) {
endAngle = option.endAngle
}
ctx.clearRect(0, 0, width, height)
ctx.beginPath()
ctx.strokeStyle = bgColor
const d: number = angleToRadian(startAngle)
const c: number = angleToRadian(bgEndAngle)
const x: number = width >> 1
const y: number = height >> 1
ctx.arc(x, y, r, d, c, !clockwise)
ctx.stroke()
ctx.closePath()
splitArc(option, x, y, r, startAngle, endAngle)
}
const splitArc = (
option: Config,
x: number,
y: number,
r: number,
start: number,
end: number
): void => {
const { ctx, clockwise, palette } = option
const splitTotal: number = Math.abs(end - start)
const j: number = clockwise ? 1 : -1
for (let i = 0; i < splitTotal; ) {
const color = palette.pickColor(Math.round((i * 255) / splitTotal))
ctx.beginPath()
setStrokeStyle(ctx, color)
const _start: number = start + i * j
let _end: number = _start + j
const mod: number = Math.abs(_start) % 90
if (mod > 20 || mod < 70) {
_end = _start + angleDistance2 * j
i += angleDistance2
} else {
i += angleDistance1
}
ctx.arc(x, y, r, angleToRadian(_start), angleToRadian(_end), !clockwise)
ctx.stroke()
}
}
const startDraw = (option: Config): void => {
let currentFrameIndex = 0
let drawFlag = true
let unLockLoop = (): void => {
drawFlag = true
setTimeout(unLockLoop, option.interval)
}
unLockLoop()
requestAnimationFrame(progress)
function progress(): void {
if (drawFlag) {
drawFlag = false
currentFrameIndex += 1
drawArc(option, currentFrameIndex)
if (currentFrameIndex >= option?.totalFramesLength) {
unLockLoop = () => {
drawFlag = false
unLockLoop = () => {}
}
return
}
}
requestAnimationFrame(progress)
}
}
const buildConfig = (options: Config, ctx: CanvasRenderingContext2D): Config => {
const option = {
...defaultConfig,
...options,
ctx,
palette: new Palette(options.colors || defaultConfig.colors),
}
option.width *= precision
option.height *= precision
option.lineWidth *= precision
option.r *= precision
return {
...option,
totalFramesLength: option.duration / option.interval,
angleChangeForFrame:
((option.endAngle - option.startAngle) * option.interval) / option.duration,
clockwise: option.endAngle - option.startAngle > 0,
}
}
const CircleProgress = (options: Partial<Config>): void => {
const canvas: HTMLCanvasElement | null = document.querySelector(`#${options.canvasId}`)
if (!canvas || !options) return
const ctx = canvas.getContext('2d')
if (!ctx) return
const option: Config = buildConfig(options as Config, ctx)
canvas.style.transform = 'scale(0.5)'
canvas.style.width = `${option.width}px`
canvas.style.height = `${option.height}px`
// @ts-ignore
canvas.style['transform-origin'] = 'left top'
setCanvasStyle(option, canvas)
setLineStyle(option)
startDraw(option)
}
CircleProgress({
canvasId: 'main-score',
r: 118, // 默认100,半径
width: 252,
height: 252, // 画布高,默认500
startAngle: 165, // 起始角度,默认180
bgEndAngle: 380, // 起始角度,默认180
endAngle: 300, // 终止角度,必须传
interval: 16, // 帧间隔时间,默认5ms
lineWidth: 16, // 描边线宽度,默认15
bgColor: 'rgba(218, 228, 247, .3)', // 背景色,默认#cccc
colors: [
[0, '#7DE4BC'],
[1, '#33C68A'],
],
duration: 1000, // 动画时间,默认2000
})
Also see: Tab Triggers